package cn.itsource.hrm.service.impl;

import cn.itsource.hrm.domain.LoginUser;
import cn.itsource.hrm.dto.LoginUserDto;
import cn.itsource.hrm.exception.Assert;
import cn.itsource.hrm.exception.BusinessException;
import cn.itsource.hrm.mapper.LoginUserMapper;
import cn.itsource.hrm.service.ILoginUserService;
import cn.itsource.hrm.util.AjaxResult;
import cn.itsource.hrm.util.HttpUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindException;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yaosang
 * @since 2022-04-04
 */
@Service
@Slf4j
public class LoginUserServiceImpl extends ServiceImpl<LoginUserMapper, LoginUser> implements ILoginUserService {

    @Autowired
    private LoginUserMapper loginUserMapper;
    @Override
    public AjaxResult addLoginUserDto(LoginUserDto loginUserDto) {
        //保存用户信息
        LoginUser loginUser = loginUserDto.getLoginUser();
        loginUserMapper.insert(loginUser);
        //保存用户和套餐中间表信息
        if(loginUserDto.getMealId() != null){
            loginUserMapper.saveLoginUserMeals(loginUser.getId(),loginUserDto.getMealId());
        }
        return AjaxResult.me().setResultObj(loginUser.getId());
    }

    @Value("${hrm.oauth2.passwordurl}")
    private String passwordUrl;

    @Override
    public Map<String, String> login(LoginUser loginUser) {

        Wrapper<LoginUser> wrapper = new EntityWrapper<>();
        wrapper.eq("username" , loginUser.getUsername());
        LoginUser loginUserFromDB = selectOne(wrapper);
        Assert.assertNotNull(loginUserFromDB,"用户名不存在");
        if(loginUserFromDB.getType().intValue() != loginUser.getType().intValue()){
            throw new BusinessException("非法请求");
        }

        //1.拼接URL：密码模式获取Token

        String clientId = "";
        String clientSecret = "";
        if(loginUser.getType().intValue() == LoginUser.USER_TYPE_SYSTEM){
            clientId = "admin";
            clientSecret = "123";
        }else if(loginUser.getType().intValue() == LoginUser.USER_TYPE_WEBSITE){
            clientId = "website";
            clientSecret = "123";
        }else{
            throw new BusinessException("非法请求");
        }

        String username = loginUser.getUsername();
        String password = loginUser.getPassword();
        String okUrl = String.format(passwordUrl ,clientId , clientSecret ,  username , password);
        log.info(okUrl);
        //2.发送请求获取Token

        //3.返回Token
        Map<String, String> map = HttpUtil.sendPost(okUrl);
        //{error_description=用户名或密码错误, error=invalid_grant}
        log.info("获取到Token {}" , map);
        if(map.containsKey("access_token")){
            //1.根据当前时间 + Token有效时长 ，来确定 ： 过期时间
            long expireTime = new Date().getTime() + Long.valueOf(map.get("expires_in")) * 1000;
            map.put("expireTime", String.valueOf(expireTime));
            return map;
        }else{
            String error_description = map.get("error_description");
            throw new BusinessException(error_description);
        }
    }
}
